package com.ruoyi.cfuser.system.service.impl;

import com.ruoyi.cfuser.api.domain.CfUser;
import com.ruoyi.cfuser.cfuser.service.ICfUserService;
import com.ruoyi.cfuser.system.service.SysCfUserService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.shop.api.domain.Shop;
import com.ruoyi.system.api.RemoteRegisterService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class SysCfUserServiceImpl implements SysCfUserService {

    @Autowired
    RedisService redisService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICfUserService cfUserService;

    @Override
    public CfUser register(CfUser cfUser) {
        cfUserService.insertCfUser(cfUser);
        return cfUser;
    }

    @Override
    public AjaxResult login(String moblie, String verifyCode, String verifyCodeToken) {

        // 检查验证码是否正确
        String redisCode = redisService.getCacheObject(verifyCodeToken);
        if (redisCode == null || !redisCode.equals(verifyCode)) {
            return AjaxResult.error("验证码错误!");
        }

        // 查询是否已经有账号
        CfUser cfUser = new CfUser();
        cfUser.setPhone(moblie);
        List<CfUser> list = cfUserService.selectCfUserList(cfUser);
        if (list == null || list.size() == 0) {
            cfUser = register(cfUser);
        }
        cfUser = list.get(0);

        LoginUser userInfo = new LoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(moblie);
        sysUser.setUserId(199999L);
        userInfo.setSysUser(sysUser);

        Map<String, Object> rspMap = tokenService.createToken(userInfo);
        rspMap.put("cfuser", cfUser);

        return AjaxResult.success(rspMap);
    }
}
